# -*- coding: utf-8 -*-
"""
@Time    : 2025/3/17 14:29 
@Author  : ZhangShenao 
@File    : 2. 图片理解.py 
@Desc    : 使用gpt-4o-mini模型,进行图片理解
"""
import base64
import os

import dotenv
from openai import OpenAI

# 加载环境变量
dotenv.load_dotenv()

# 创建OpenAI客户端
client = OpenAI(base_url=os.getenv("OPENAI_API_BASE"))

# 读取本地图片并进行base64编码
with open("./data/cat.png", "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read()).decode('utf-8')

# 调用chat.completions.create接口,并指定content type为图片
response = client.chat.completions.create(
    model="gpt-4o-mini",  # 使用gpt-4o-mini模型
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "给我讲下这张图片描绘了什么，用中文回答。"},
                {
                    "type": "image_url",  # 指定content类型为image_url,并将本地图片的base64编码后的路径传递过去
                    "image_url": {
                        "url": f"data:image/png;base64,{encoded_image}",
                    }
                },
            ],
        }
    ],
    max_tokens=300,
)

# 打印结果
print(response.choices[0].message.content)
